<template>
  <div>
    <canvas ref="myCanvas" width="400" height="300" style="border: 1px solid #000000"></canvas>
  </div>
</template>


<script>
export default {
  name: "shangpinSort",
  components: {},
  data() {
    return {};
  },
  methods: {},
  created() {},
  mounted() {
    //获取画布的dom对象
    var canvas = this.$refs.myCanvas;
    //获取画布
    var ctx = canvas.getContext("2d");

    //表示方块的类
    function Block(x, y, speed) {
      this.x = x || 20; //方块的x坐标，默认为20
      this.y = y || 20; //方块的y坐标，默认为20
      this.speed = speed || 5; //方块的移动速度，默认为5

      //向上移动
      this.moveUp = function () {
        this.y -= this.speed;
        if (this.y < 0) {
          //防止超出上边界
          this.y = 0;
        }
      };

      //向右移动
      this.moveRight = function () {
        this.x += this.speed;
        var maxX = canvas.width - 20;
        if (this.x > maxX) {
          //防止超出右边界
          this.x = maxX;
        }
      };

      //向左移动
      this.moveLeft = function () {
        this.x -= this.speed;
        if (this.x < 0) {
          //防止超出左边界
          this.x = 0;
        }
      };

      //向下移动
      this.moveDown = function () {
        this.y += this.speed;
        var maxY = canvas.height - 20;
        if (this.y > maxY) {
          //防止超出下边界
          this.y = maxY;
        }
      };
    }

    //绘制方块
    function drawBlock(block) {
      if (typeof ctx != "undefined") {
        ctx.beginPath();
        ctx.fillRect(block.x, block.y, 20, 20);
        ctx.fill();
      }
    }

    //清空canvas画布
    function clearCanvas() {
      if (typeof ctx != "undefined") {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
      }
    }

    //绘制初始方块
    var block = new Block();
    drawBlock(block);

    //onkeydown事件的回调处理函数
    //根据用户的按键来控制方块的移动
    document.onkeydown = function (event) {
      switch (event.keyCode) {
        case 37: //左方向键
          block.moveLeft();
          break;
        case 38: //上方向键
          block.moveUp();
          break;
        case 39: //右方向键
          block.moveRight();
          break;
        case 40: //下方向键
          block.moveDown();
          break;
        default:
          //其他按键操作不响应
          return;
      }

      clearCanvas(); //先清空画布
      drawBlock(block); //再绘制最新的方块
    };
  },
};
</script>

<style>
</style>